package com.kamkor.interviewer.client.view;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.Label;
import com.kamkor.interviewer.client.event.SaveAllEvent;
import com.kamkor.interviewer.client.presenter.DisplaysSaveInfo;

/**
 * When text change happens, this handler will set message in saveInfoDisplay
 * 
 * Message like: Text is not saved
 *
 * @author kamkor
 *
 */
public class TextChangedHandler implements ChangeHandler {
	/** Display that contains label, which text is changed by this Handler */
	private DisplaysSaveInfo saveInfoDisplay;
	
	/** Text that is displayed when change occurs */
	private String textToDisplay;
	
	private HandlerManager eventBus;
	
	/**
	 * @param saveInfoDisplay Display that contains label, which text is changed by this Handler.
	 * @param textToDisplay Display this text when change occurs. 
	 */
	public TextChangedHandler(DisplaysSaveInfo saveInfoDisplay, String textToDisplay) {
		this.saveInfoDisplay = saveInfoDisplay;
		this.textToDisplay = textToDisplay;
	}	
	
	/**
	 * When TextChangeHandler has eventbus, it will fire SaveAllEvent event when Text is changed
	 * 
	 * @param eventBus 
	 * @param saveInfoDisplay Display that contains label, which text is changed by this Handler.
	 * @param textToDisplay Display this text when change occurs. 
	 */
	public TextChangedHandler(HandlerManager eventBus, DisplaysSaveInfo saveInfoDisplay, String textToDisplay) {
		this(saveInfoDisplay, textToDisplay);
		this.eventBus = eventBus;
	}	
	
	/**
	 * Changes display label style to textNotSaved and displays  textToDisplay
	 * that was send as parameter to constructor to this Handler
	 */
	@Override
	public void onChange(ChangeEvent event) {		
		Label isSavedInfo = saveInfoDisplay.getIsSavedInfo();
		
		if (isSavedInfo != null) {
			isSavedInfo.setText(textToDisplay);
			isSavedInfo.setStyleName("textNotSaved");
			if (eventBus != null && saveInfoDisplay.isAutoSave()) { 
				eventBus.fireEvent(new SaveAllEvent());
			}
		}
	}
}
